import Hero from "./Hero";
import Carry from "./Carry";

/**
 * 游戏类
 */

 export default class Game extends Laya.Script {

    constructor() { super() }

    // 英雄预制体
    /** @prop {name:hero,tips:"英雄预制体",type:Prefab}*/
    private hero: Laya.Prefab;

    // 搬运工预制体
    /** @prop {name:carry,tips:"搬运工预制体",type:Prefab}*/
    private carry: Laya.Prefab;

    public levelArr: Array<number> = [0, 0, 0
                                    , 0, 0, 0
                                    , 0, 0, 0
                                    , 0, 0, 0]  // 英雄排列
    public platformArr: Array<Laya.Sprite> = [] // 平台列表
    public heroMap: any // 英雄实例列表
    public carryList: Array<Laya.Sprite> = [] // 搬运列表

    private addList: Array<Laya.Sprite> = [] // 新增按钮列表

    private gold: Laya.Text
    private goldNum: number = 0 // 金币

    onEnable(): void {
        this.heroMap = {}
        for (let i = 0; i < 12; i++) {
            this.platformArr.push(
                this.owner.getChildByName('platform_' + i) as Laya.Sprite
            )
            this.heroMap[i] = undefined
        }

        // 拖拽结束
        Laya.stage.on('drag_end', this, this.dragEnd)

        for (let i = 1; i <= 6; i++) {
            let addBtn = this.owner.getChildByName('new_' + i) as Laya.Sprite
            this.addList.push(addBtn)
            addBtn.on(Laya.Event.CLICK, this, this.newHero, [i, -1])
        }
        
        

        this.gold = this.owner.getChildByName('gold') as Laya.Text
        this.setGold(100)

        this.addListener()
    }

    // 添加监听事件
    private addListener(): void {
        Laya.stage.on('goldAdd', this, level => {
            this.setGold(this.goldNum + level * 100)
        })
    }

    // 拖拽结束
    private dragEnd(data: Laya.Sprite): void {
        // 获取第一个碰到得平台
        let index = -1
        for (let i = 0; i < 12; i++) {
            if (_boom(this.platformArr[i], data)) {
                index = i
                break
            }
        }
        let hero = data.getComponent(Hero)
        if (index > -1 && hero.index != index) { // 碰到了
            if (this.levelArr[index] == 0) { // 空位直接填充
                this.fill(data, index)
            }
            else if (hero.level == this.levelArr[index]) { // 等级相同 合并
                let level = hero.level + 1
                // 清除数组
                this.levelArr[hero.index] = 0
                this.levelArr[index] = 0
                // 清除对象
                this.heroMap[hero.index].removeSelf()
                this.heroMap[index].removeSelf()
                this.heroMap[hero.index] = undefined
                this.heroMap[index] = undefined
                // 创建一个新的更高等级得英雄
                this.newHero(level, index)
            } else { // 拖拽失败
                hero.setIndex(hero.index, this.platformArr[hero.index]) // 还原位置
            }
        } else {
            hero.setIndex(hero.index, this.platformArr[hero.index]) // 还原位置
        }
    }

    // 填充
    private fill(target:Laya.Sprite, index: number) {
        let hero = target.getComponent(Hero)
        this.levelArr[hero.index] = 0 // 交换两个位置得值
        this.levelArr[index] = hero.level // 交换两个位置得值
        this.heroMap[index] = this.heroMap[hero.index] // 交换两个位置得值
        this.heroMap[hero.index] = undefined // 交换两个位置得值
        hero.setIndex(index, this.platformArr[index]) // 设置英雄位置
    }

    // 新建一个英雄
    private newHero(level:number, index: number) {
        if (this.goldNum < Math.pow(2, level - 1) * 100 && index == -1) { // index = -1 购买   x > -1 合并
            alert('钱不够啊！')
            return
        }
        let i = this.levelArr.findIndex(e => e == 0)
        if (index || i > -1) { // 有空位
           
            if (index > -1) {
                i = index
            } else {
                // 扣钱先写道这里吧
                this.setGold(this.goldNum - Math.pow(2, level - 1) * 100)
            }
            let hero: Laya.Sprite = Laya.Pool.getItemByCreateFun("hero", this.hero.create, this.hero);
            this.heroMap[i] = hero
            this.owner.addChild(hero);
            let c = hero.getComponent(Hero)
            c.setLevel(level)
            c.setIndex(i, this.platformArr[i])
            this.levelArr[i] = level
            this.updateCarryList(this.levelArr)


        } else { // 无空位
            alert('没有位置了')
        }
    }


    // 更新搬矿的英雄列表
    private updateCarryList(arr: Array<number>): void {
        let newArr = []
        arr.forEach(e => {
            if (e) {
                newArr.push(e)
            }
        })
        newArr.sort((a, b) => b - a)
        let num = newArr.length - this.carryList.length
        // 保持长度一致
        if (num >= 0) { // 增加了
            for (let i = 0; i < num ; i++) {
                let carry: Laya.Sprite = Laya.Pool.getItemByCreateFun("carry", this.carry.create, this.carry);
                this.carryList.push(carry)
                this.owner.addChild(carry);
            }
        } else { // 减少了
            for (let i = 0; i < -num; i++) {
                let carry = this.carryList.pop()
                let c = carry.getComponent(Carry)
                c.stopAction()
                carry.removeSelf()
            }
        }
        // 更新等级
        setTimeout(() => {
            for (let i = 0; i < newArr.length; i++) {
                let c = this.carryList[i].getComponent(Carry)
                c.setLevel(newArr[i])
            }
        }, 100)
    }

    // 设置金币
    private setGold(num: number) {
        this.goldNum = num
        this.gold.text = '金币：' + this.goldNum

        this.addList.forEach((e, i) => {
            let money = Math.pow(2, i) * 100
            if (this.goldNum < money) { // 买不起
                e.loadImage('images/buy_'+(i+1)+'_none.png')
            } else { // 买得起
                e.loadImage('images/buy_'+(i+1)+'.png')
            }
        })
    }

 }


 // 碰撞检测
 function _boom(a: Laya.Sprite, b: Laya.Sprite) {
     if (
        b.x + (b.width / 2) > a.x &&
        b.x + (b.width / 2) < a.x + a.width &&
        b.y + b.height > a.y &&
        b.y + b.height < a.y + a.height
     ) {
         return true
     }
     return false
 }